package com.yulian.web_api.system_management;
 

import java.util.ArrayList;
import java.util.List;
  
import com.yulian.repository.CommonRepositoryImpl;
import com.yulian.repository.system_management.AuthorizationRepositoryImpl;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory; 
import io.vertx.core.Future;
import io.vertx.core.Promise; 
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet; 
/**
 * 该类位于业务逻辑层，用于数据访问的权限管理，保存前端从系统菜单中选择的某个角色拥有权限的部分菜单；读取角色所拥有的权限的业务逻辑管理，
 * 为MainVerticle中的REST接口提供服务  
 * @author 余大勇
 *
 */
public class AuthorizationManager {
	
	final InternalLogger logger = Log4JLoggerFactory.getInstance(AuthorizationManager.class); 
	CommonRepositoryImpl commonRepository = new CommonRepositoryImpl();
	AuthorizationRepositoryImpl authorizationRepository = new AuthorizationRepositoryImpl(); 
	/**
	 * 获取前端每一个页面具有的按钮权限
	 * @param client
	 * @param config
	 * @param bodyJSObj
	 * @return
	 */
	public Future<JsonObject> getAuth(PgPool client, JsonObject bodyJSObj, User user) {
	    int user_id = user.attributes().getJsonObject("accessToken").getInteger("userId");
        Promise<JsonObject> promise = Promise.promise();
        // 最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 从bodyJson中获取数据
        String parent_name = bodyJSObj.getString("parent_name");
           
        this.commonRepository.getCon(client)
        .onSuccess(conn -> {
            this.authorizationRepository.getAuth(conn, user_id,parent_name).onComplete(ar -> {
                if (ar.failed()) {
                    responseJSObj.put("code", -1);
                    responseJSObj.put("msg", ar.cause().getMessage());
                    promise.complete(responseJSObj);
                } else {
                    RowSet<Row> rows = ar.result();
                    List<String> authList = new ArrayList<String>();
                    rows.forEach(item -> {
                    	authList.add(item.getString("menu_name")); 
                    });
                    logger.info("为页面 {} 获取的按钮集合:{}",parent_name, authList.toString());
                    //将列表转为字符串数组 
                    responseJSObj.put("data", authList.toArray(new String[authList.size()])); 
                    promise.complete(responseJSObj); 
                }
            });
        })
        .onFailure(err -> {
            responseJSObj.put("code", -1);
            responseJSObj.put("msg", "连接数据库报错: " + err.getMessage());
            promise.complete(responseJSObj);
        });
        return promise.future();
    }
	
	 

}
